package com.coocaa.x.framework.app;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LiteHandlerThread;
import com.coocaa.x.service.liteupgrade.LiteUpgradeKernel;
import com.coocaa.x.service.liteupgrade.aidl.UpgradeParams;
import com.coocaa.x.service.liteupgrade.aidl.ILiteUpgradeService;
import com.coocaa.x.service.liteupgrade.aidl.UpgradeInfo;

public class UpgradeManager {

    private static ILiteUpgradeService service = null;

    private static synchronized void binService(Context context) {
        LiteHandlerThread.checkMainThread();
        if (service == null) {
            Intent intent = new Intent("com.coocaa.x.service.liteupgrade");
            intent.setPackage(context.getPackageName());
            try {
                context.startService(intent);
                context.bindService(intent, new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder binder) {
                        service = ILiteUpgradeService.Stub.asInterface(binder);
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                        service = null;
                    }
                }, Context.BIND_AUTO_CREATE);
                while (service == null)
                    Thread.sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void checkKernel() {
        Object obj = Android.getMetaData(CoocaaApplication.getContext(), CoocaaApplication.getContext().getPackageName(), LiteUpgradeKernel.META_NAME);
        if (obj == null)
            throw new RuntimeException("Are you kidd me?? No upgradekernel has been config in manifest!!");
    }

    public static synchronized String exec(String cmd, UpgradeParams params) {
        checkKernel();
        binService(CoocaaApplication.getContext());
        try {
            if (params == null)
                params = new UpgradeParams();
            return service.exec(cmd, params);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static synchronized UpgradeInfo checkUpgrade(UpgradeParams params) {
        checkKernel();
        binService(CoocaaApplication.getContext());

        try {
            return service.checkUpgrade(params);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return null;
    }
}
